package cc.jq1024.domain.strategy.service.rule.tree.impl;

import cc.jq1024.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cc.jq1024.domain.strategy.model.valobj.StrategyAwardStockKeyVO;
import cc.jq1024.domain.strategy.repository.IStrategyRepository;
import cc.jq1024.domain.strategy.service.armory.IStrategyDispatch;
import cc.jq1024.domain.strategy.service.rule.tree.ILogicTreeNode;
import cc.jq1024.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 库存节点 -》 将库存操作也抽象为一种规则
 * @Date: 2024-04-16-13:56
 */
@Slf4j
@Component("rule_stock")
@AllArgsConstructor
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    private final IStrategyDispatch strategyDispatch;

    private final IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Long awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
        // 扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId, awardId, endDateTime);
        if (Boolean.TRUE.equals(status)) {
            log.info("规则过滤-库存扣减-成功 userId:{} strategyId:{} awardId:{}", userId, strategyId, awardId);
            // 写入延迟队列，延迟消费更新数据库记录。【在trigger的job；UpdateAwardStockJob 下消费队列，更新数据库记录】
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue(ruleValue)
                            .build())
                    .build();
        }

        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .build();
    }
}
